<?php

/**
 * 热词模块
 */

namespace app\api\controller;

use app\common\controller\Common;
use app\common\extract\ExtractFactory;
use app\common\extract\Excel;
use app\common\Script;
use think\Db;

class Hotwords extends Common
{
    protected $model;
    public function __construct()
    {
        parent::_initialize();
        $this->model = Model('HotWord');
        if (empty(cache('DB_HW_CONFIG_DATA'))) {
            cache('DB_HW_CONFIG_DATA', Model('HotwordConfig')->getDataList());
        }
    }
    /**
     * 获取热词一级页面的信息，默认配置和热词生成模型的状态
     */
    public function fileIndex()
    {
        if (cache('DB_HW_CONFIG_DATA')['STATE'] == 2 && (time() - cache('DB_HW_CONFIG_DATA')['START_TIME']) > 60 * config("COST_TIME")) {

            \app\common\Hook::call('HotwordEnable', 'Enabled');
        }
        return resultArray(['data' => cache('DB_HW_CONFIG_DATA')]);
    }

    /**
     * 热词文件列表获取
     * @page    分页页数
     * @limit   分页每页数据数量
     */
    public function fileList(int $limit = 10, int $page = 1)
    {
        $result = $this->model->getFileList($limit, $page);
        if (!$result) {
            return resultArray(['error' => $this->model->getError()]);
        }
        return resultArray(['data' => $result]);
    }

    /**
     * 删除热词文件
     * @id  热词文件的主键id
     */
    public function fileDelete()
    {
        if (!$this->param['id']) {
            return resultArray(['error' => '参数错误']);
        }
        // if (cache('DB_HW_CONFIG_DATA')['STATE'] == 2) {
        //     return resultArray(['error' => '模型生成中']);
        // }
        $result = $this->model->updateDataById(array('is_delete' => 1, 'update_time' => time()), $this->param['id']);
        if (!$result) {
            return resultArray(['error' => $this->model->getError()]);
        }
        //更新热词后的钩子
        //\app\common\Hook::call('HotwordEnable', 'WillEnable');
        return resultArray(['data' => '']);
    }

    /**
     * 上传热词文件
     * 参数
     * 用户 user_id
     * 文件 file
     * 主题  title
     * 文件描述  describe
     */
    public function fileCreate()
    {
        //修改跨域
        header("Access-Control-Allow-Origin: *");
        //不是post传递，返回请求类型错误
        if (!request()->isPost()) {
            return resultArray(['error' => '请求类型错误']);
        }
        // if (cache('DB_HW_CONFIG_DATA')['STATE'] == 2) {
        //     return resultArray(['error' => '模型生成中']);
        // }
        //热词模型实例
        //$model = Model('HotWord');
        // $count = $model->where('is_delete', '=', 0)->count();
        // if ($count >= 10) {
        //     return resultArray(['error' => '热词数已经达到10个，不能上传']);
        // }
        if (empty(request()->file('file'))) {
            return resultArray(['error' => '请选择文件']);
        }
        //判断是否有上传文件
        //获取后缀
        $ext = substr(strrchr(request()->file('file')->getInfo()['name'], '.'), 1);
        $extract = ExtractFactory::createExtract($ext);
        if (!$extract) {
            return resultArray(['error' => '上传文件格式错误']);
        }
        //去除空值
        $file_data = array_filter($extract->setFile(request()->file('file')->getInfo()['tmp_name'])->getArray());
        //$file_data = $extract->getArray();
        if (count($file_data) > 2000) {
            return resultArray(['error' => '上传文件热词数量超过2000,不能上传']);
        }

        if (isset($this->param['id'])) {
            if ($this->model->get($this->param['id'])->status == 3) {
                return resultArray(['error' => '热词模型更新中']);
            }
            //删除之前的热词文件
            $this->model->get($this->param['id'])->delete();
        }

        $this->param['create_time'] = $this->param['update_time'] = time();
        $this->param['filename'] = request()->file('file')->getInfo()['name'];
        $this->param['content'] = json_encode($file_data);
        $this->param['total'] = count($file_data);
        $this->param['formatname'] = $this->formatUploadName(request()->file('file')->getInfo()['name']);
        $this->param['filenamemd5'] = '';
        $this->param['title'] = $this->param['title'] ? $this->param['title'] : $this->param['filename'];
        //保存文件
        $info = request()->file('file')->validate(['size' => 99999999, 'ext' => 'txt,xls,xlsx,doc,docx'])->move(config("huisheng.hot_word_upload_path"), $this->param['formatname']);
        if (!$info) {
            return resultArray(['error' => '上传文件格式或大小错误']);
        }
        //插入
        $result = $this->model->createData($this->param);
        if (!$result) {
            return resultArray(['error' => $this->model->getError()]);
        }
        //更新热词后的钩子
        //\app\common\Hook::call('HotwordEnable', 'WillEnable');
        return resultArray(['data' => '']);
    }

    /**
     * 热词文件的详情
     * 参数
     * id  热词列表id
     */
    public function fileDetail()
    {
        //修改跨域
        header("Access-Control-Allow-Origin: *");
        if (!$this->param['id']) {
            return resultArray(['error' => 'id为空']);
        }
        //通过数据库数据检索是否有热词文件
        $result = $this->model->getFileDetail($this->param['id']);
        if (!$result) {
            return resultArray(['error' => $this->model->getError()]);
        }
        return resultArray(['data' => $result]);
    }

    /**
     * 热词文件下载
     * @id 热词id
     */
    public function fileDownload()
    {
        if (!$this->param['id']) {
            return resultArray(['error' => 'id为空']);
        }
        $_file = $this->model->get(['id' => $this->param['id'], 'is_delete' => 0]);
        if (!$_file) {
            return resultArray(['error' => '暂无此数据']);
        }
        $path = config("huisheng.hot_word_upload_path") . DS . pathinfo($_file->formatname)['file'] . ".xlsx";
        //依赖注入
        Excel::createFile(json_decode($_file->content, true), $path);
        //设置路径，下载
        download_result_one($path, $_file->title);
    }

    /**
     * 热词文件中的热词添加
     */
    public function addWords()
    {
        //请求类型判断
        if (!request()->isPost()) {
            return resultArray(['error' => '请求类型错误']);
        }
        // if (cache('DB_HW_CONFIG_DATA')['STATE'] == 2) {
        //     return resultArray(['error' => '模型生成中']);
        // }
        if (!$this->param['id']) {
            return resultArray(['error' => 'id为空']);
        }
        //检索热词文件
        $result = $this->model->addFileWords($this->param['id'], $this->param['words']);
        if (!$result) {
            return resultArray(['error' => $this->model->getError()]);
        }
        //更新热词后的钩子
        //\app\common\Hook::call('HotwordEnable', 'WillEnable');
        return resultArray(['data' => '']);
    }

    /**
     * 文件中的热词修改
     * @id   热词id
     * @words 字符串 新热词集
     */
    public function editWords()
    {
        //请求类型判断
        if (!request()->isPost()) {
            return resultArray(['error' => '请求类型错误']);
        }
        // if (cache('DB_HW_CONFIG_DATA')['STATE'] == 2) {
        //     return resultArray(['error' => '模型生成中']);
        // }
        if (!$this->param['id']) {
            return resultArray(['error' => 'id为空']);
        }
        $result = $this->model->editFileWords($this->param['id'], $this->param['words']);
        if (!$result) {
            return resultArray(['error' => $this->model->getError()]);
        }
        //更新热词后的钩子
        //\app\common\Hook::call('HotwordEnable', 'WillEnable');
        return resultArray(['data' => '']);
    }



    /**
     * 热词模型生成
     */
    public function modelOn($id, $type = 'pinyin')
    {
        //热词文件字符串
        // if (cache('DB_HW_CONFIG_DATA')['STATE'] == 2) {
        //     return resultArray(['error' => '模型生成中']);
        // }
        try {
            $_contents = $this->model->get($id);
            if (!$_contents) {
                return resultArray(['error' => '未找到热词文件']);
            }
            if ($_contents->status == 3) {
                return resultArray(['error' => '热词模型生成中！']);
            }
            //执行脚本生成热词文件
            if (!$this->makefile($_contents)) {
                return resultArray(['error' => '文件被占用']);
            }
            //添加到队列中
            $push = [
                'sid' => $id,   //场景id
                'hid' => $id,   //热词id
                'type' => $type //格式
            ];
            self::$redis->pushHotWord($push);
            //修改状态
            $result = Db::name('hot_word')->where('id',$id)->where('status', '<>', 3)->update(['status' => 3]);
            if(!$result){
                return resultArray(['error' => '热词模型生成中！']);
            }
            //启动生成模型的钩子
            //\app\common\Hook::call('HotwordEnable', 'Enabling');
            return resultArray(['data' => '']);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求错误']);
        }
    }

    protected function makefile($model)
    {
        $content = implode("\n", array_unique(json_decode($model->content, true)));
        //打开文件 清空内容 输入热词数据
        $file = fopen(config('huisheng.HOT_WORD_PATH') . $model->formatname, 'w');
        if (flock($file, LOCK_EX)) {
            fwrite($file, $content);
            fclose($file);
        } else {
            fclose($file);
            return false;
        }
        return true;
    }

    /**
     * 修改生成热词模型启用状态
     * @status 1代表更新成功，3代表热词相同不做修改
     */
    public function hotwordModelChangeStatus($status = 1)
    {
        if (input('param.status') !== null) {
            //根据值做一些事情
        }
        //热词模型生成结束的钩子
        //\app\common\Hook::call('HotwordEnable', 'Enabled');
        return resultArray(['data' => '']);
    }

    /**
     * 热词文集模板下载
     */
    public function templateDownload()
    {
        if (!is_file(config("huisheng.hot_word_model_path"))) {
            //依赖注入
            Excel::createFile(array('热词需逐行排列', '热词1', '热词2', '热词3', '热词4', '... ...'), config("huisheng.hot_word_model_path"));
        }
        //设置路径，下载
        download_result_one(config("huisheng.hot_word_model_path"), '热词列表模板');
    }

    /**
     * 热词生成百分比
     */
    public function percent()
    {
        if (!cache('DB_HW_CONFIG_DATA')['START_TIME']) {
            return resultArray(['data' => ['percent' => 100]]);
        }
        $percent = round((time() - cache('DB_HW_CONFIG_DATA')['START_TIME']) * 100 / (60 * config("COST_TIME")), 2);
        if ($percent >= 100) {
            return resultArray(['data' => ['percent' => 99.99]]);
        }
        return resultArray(['data' => ['percent' => $percent]]);
    }


    /**
     * 格式化文件名字
     * 参数
     * filename 当前上传文件名字
     */
    public function formatUploadName($filename)
    {
        //截取当前上传文件的后缀
        $ext = substr(strrchr($filename, '.'), 1);
        //格式化名字
        $formatname = trim(date('YmdHis', time()) . rand(1000, 9999) . "." . $ext);
        return $formatname;
    }
}
